using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;

namespace CodRevit.ViewModels
{
    public partial class DeleteFilterViewModel : ObservableObject
    {
        private readonly UIApplication _uiapp;
        private readonly Document _doc;
        private readonly Window _window;

        [ObservableProperty]
        private ObservableCollection<ParameterFilterElement> _filters;

        [ObservableProperty]
        private ObservableCollection<ParameterFilterElement> _selectedFilters;

        [ObservableProperty]
        private string _status = "请选择要删除的过滤器";

        public DeleteFilterViewModel(UIApplication uiapp, Window window)
        {
            _uiapp = uiapp;
            _doc = uiapp.ActiveUIDocument.Document;
            _window = window;

            // 获取所有过滤器
            Filters = new ObservableCollection<ParameterFilterElement>(
                new FilteredElementCollector(_doc)
                    .OfClass(typeof(ParameterFilterElement))
                    .Cast<ParameterFilterElement>()
                    .OrderBy(f => f.Name));

            SelectedFilters = new ObservableCollection<ParameterFilterElement>();
        }

        [RelayCommand]
        private void DeleteFilters()
        {
            if (!SelectedFilters.Any())
            {
                Status = "请先选择要删除的过滤器";
                return;
            }

            var result = MessageBox.Show(
                $"确定要删除选中的 {SelectedFilters.Count} 个过滤器吗？",
                "确认删除",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    using (Transaction trans = new Transaction(_doc, "删除过滤器"))
                    {
                        trans.Start();
                        foreach (var filter in SelectedFilters)
                        {
                            _doc.Delete(filter.Id);
                        }
                        trans.Commit();
                    }

                    // 删除成功后直接关闭窗口
                    _window.Close();
                }
                catch (System.Exception ex)
                {
                    Status = $"删除失败: {ex.Message}";
                }
            }
        }
    }
}